package org.dromara.system.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.BusinessException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.converter.MachineConverters;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.SysUserWithdrawalPolicy;
import org.dromara.system.domain.bo.InitWithdrawalPolicyBo;
import org.dromara.system.domain.bo.SysUserWithdrawalPolicyBo;
import org.dromara.system.domain.vo.SysUserWithdrawalPolicyVo;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.mapper.SysUserWithdrawalPolicyMapper;
import org.dromara.system.service.ISysUserWithdrawalPolicyService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 提现政策Service业务层处理
 *
 * @author Lion Li
 * @date 2025-07-16
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysUserWithdrawalPolicyServiceImpl extends ServiceImpl<SysUserWithdrawalPolicyMapper, SysUserWithdrawalPolicy> implements ISysUserWithdrawalPolicyService {


    private final SysUserMapper sysUserMapper;

    /**
     * 查询提现政策
     *
     * @param id 主键
     * @return 提现政策
     */
    @Override
    public SysUserWithdrawalPolicyVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询提现政策列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 提现政策分页列表
     */
    @Override
    public TableDataInfo<SysUserWithdrawalPolicyVo> queryPageList(SysUserWithdrawalPolicyBo bo, PageQuery pageQuery) {
        IPage<SysUserWithdrawalPolicyVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        IPage<SysUserWithdrawalPolicyVo> list = baseMapper.findAll(page, bo);
        return TableDataInfo.build(list);
    }

    /**
     * 查询符合条件的提现政策列表
     *
     * @param bo 查询条件
     * @return 提现政策列表
     */
    @Override
    public List<SysUserWithdrawalPolicyVo> queryList(SysUserWithdrawalPolicyBo bo) {
        LambdaQueryWrapper<SysUserWithdrawalPolicy> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysUserWithdrawalPolicy> buildQueryWrapper(SysUserWithdrawalPolicyBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysUserWithdrawalPolicy> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(SysUserWithdrawalPolicy::getId);
        lqw.eq(bo.getUserId() != null, SysUserWithdrawalPolicy::getUserId, bo.getUserId());
        lqw.eq(bo.getRate() != null, SysUserWithdrawalPolicy::getRate, bo.getRate());
        lqw.eq(bo.getMinus() != null, SysUserWithdrawalPolicy::getMinus, bo.getMinus());
        return lqw;
    }

    /**
     * 新增提现政策
     *
     * @param bo 提现政策
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SysUserWithdrawalPolicyBo bo) {
        SysUserWithdrawalPolicy add = MapstructUtils.convert(bo, SysUserWithdrawalPolicy.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改提现政策
     *
     * @param bo 提现政策
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SysUserWithdrawalPolicyBo bo) {
        Long userId = bo.getUserId();
//        SysUser sysUser = sysUserMapper.selectById(userId);
//        Long pId = sysUser.getPId();
//        SysUserWithdrawalPolicy pUserWithdrawalPolicy = lambdaQuery().eq(SysUserWithdrawalPolicy::getUserId, pId).one();
//        BusinessException.isNull(pUserWithdrawalPolicy, "上级提现税点为空！");
//        BigDecimal rate = pUserWithdrawalPolicy.getRate();
//        BigDecimal minus = pUserWithdrawalPolicy.getMinus();
//        BusinessException.isTrue(NumberUtil.isLess(bo.getRate(), rate) || NumberUtil.isLess(bo.getMinus(), minus)
//            , "该用户上级提现税点为" + rate + "+" + minus + ",设置的值需要大于上级");
        SysUserWithdrawalPolicy update = MapstructUtils.convert(bo, SysUserWithdrawalPolicy.class);
        SysUserWithdrawalPolicy sysUserWithdrawalPolicy = lambdaQuery().eq(SysUserWithdrawalPolicy::getUserId, userId).one();
        if (ObjectUtil.isNull(sysUserWithdrawalPolicy)) {
            //新增
            saveOrUpdate(update);
        } else {
            //修改
            lambdaUpdate()
                .set(SysUserWithdrawalPolicy::getRate, update.getRate())
                .set(SysUserWithdrawalPolicy::getMinus, update.getMinus())
                .eq(SysUserWithdrawalPolicy::getUserId, userId)
                .update();
        }
        return Boolean.TRUE;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysUserWithdrawalPolicy entity) {
        //TODO 做一些数据校验,如唯一约束
        Long userId = entity.getUserId();
        SysUserWithdrawalPolicy sysUserWithdrawalPolicy = lambdaQuery().eq(SysUserWithdrawalPolicy::getUserId, userId).one();
        BusinessException.notNull(sysUserWithdrawalPolicy, "该用户已拥有提现政策！");
    }

    /**
     * 校验并批量删除提现政策信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public void initWithdrawalPolicy(InitWithdrawalPolicyBo bo) {
        SysUserWithdrawalPolicy sysUserWithdrawalPolicy = lambdaQuery().eq(SysUserWithdrawalPolicy::getUserId, bo.getPId()).one();
        SysUserWithdrawalPolicy build = SysUserWithdrawalPolicy.builder()
            .userId(bo.getUserId()).rate(sysUserWithdrawalPolicy.getRate())
            .minus(sysUserWithdrawalPolicy.getMinus()).build();
        super.save(build);
    }

    @Override
    public SysUserWithdrawalPolicyVo queryUserWithdrawalPolicy(SysUserWithdrawalPolicyBo bo) {
        if (ObjectUtil.isNull(bo.getUserId())) {
            bo.setUserId(LoginHelper.getUserId());
        }
        SysUserWithdrawalPolicy sysUserWithdrawalPolicy = lambdaQuery().eq(SysUserWithdrawalPolicy::getUserId, bo.getUserId()).one();
        return MachineConverters.INSTANCE.toSysUserWithdrawalPolicyVo(sysUserWithdrawalPolicy);
    }
}
